//
//  LocationManager.swift
//  iFishApp
//
//  Created by Bob on 2022/3/4.
//

import SwiftUI
import CoreLocation

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    
    @Published var manager: CLLocationManager = CLLocationManager()
    
    @Published var cityName: String?
    
    override init() {
        super.init()
        manager.delegate = self
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last?.coordinate else {
            return
        }
        
        let geo = CLGeocoder()
        geo.reverseGeocodeLocation(CLLocation(latitude: location.latitude, longitude: location.longitude)) { placemarks, err in
            
            guard let placemark = placemarks?.first else {
                return
            }
            
            guard let name = placemark.locality else {
                return
            }
            
            DispatchQueue.main.async {
                self.cityName = String(name.prefix(name.count - 1))
            }
            
        }
        
    }
    
}
